package com.teach3;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * <pre>
 * - 屏幕广播接收 
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2021-4-29 15:14:52
 * Version : 1.0
 * Copyright 2021 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 */
public class Screen extends JFrame {
	
	public static void main(String[] args) {
		new Screen().setVisible(true);
	}
	
	public Screen() {
		setTitle("屏幕");
		setSize(400, 300);
		JPanel j = new Sc();
		setContentPane(j);
		setLocationRelativeTo(null);
	}
	
	private class Sc extends JPanel {
		
		private BufferedImage img;
		
		public Sc() {
			try {
				DatagramSocket serverSocket = new DatagramSocket(5000);
				
				byte[] arr = new byte[65536];
				// 数据包的 大小 <=64k
				DatagramPacket packet = new DatagramPacket(arr, 65536);

				
				new Thread(()->{
					while(true){
						try{
							serverSocket.receive(packet);
							// 从包中将数据取出
							byte[] arr1 = packet.getData();
							ByteArrayInputStream in = new ByteArrayInputStream(arr1, 0, packet.getLength());
							img = ImageIO.read(in);
							repaint();
						}catch(Exception ex){
							break;
						}
					}
				}).start();
				
				

				

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		@Override
		public void paint(Graphics g) {
			if(img!=null){
				g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), Color.BLACK, null);
			}else{
				super.paint(g);
			}
		}
	}

}
